package com.gim.util;

import io.netty.channel.Channel;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class ChannelManager {

    // 线程安全：存储用户ID -> Channel 的映射
    private final Map<String, Channel> userChannelMap = new ConcurrentHashMap<>();

    // 可选：Channel -> 用户ID 反向映射（用于连接断开时清理）
    private final Map<Channel, String> channelUserMap = new ConcurrentHashMap<>();

    public void addChannel(String userId, Channel channel) {
        userChannelMap.put(userId, channel);
        channelUserMap.put(channel, userId);
    }

    public void removeChannel(Channel channel) {
        String userId = channelUserMap.remove(channel);
        if (userId != null) {
            userChannelMap.remove(userId);
        }
    }

    public boolean sendToUser(String userId, Object message) {
        Channel channel = userChannelMap.get(userId);
        if (channel != null && channel.isActive()) {
            channel.writeAndFlush(message);
            return true;
        }
        return false; // 用户不在线
    }

    public Set<String> getOnlineUsers() {
        return new HashSet<>(userChannelMap.keySet());
    }
}